<template>
  <div class="row">
    <div class="col-md-12">
      <FrontSideTable
        v-show="currentView === 0"
        ref="table"
        :dataUrl="rootUrl+'/getSelectedBridges'"
        :dataParam="dataParam"
        :tableTitle="tableTitle"
        :columns="columns"
        searchHint="输入关键字查找，多个关键字用空格隔开"
        :searchProps="searchProps"
        @onBack="handleBack"
        @onCreated="handleCreated"
        :addable="false"
        canBack
        customButton
        customFormDialog>
        <!--表格上方按钮-->
        <template slot="buttonArea">
          <el-button v-if="isManager" :loading="allPassLoading" style="margin-left:0" size="mini" @click="passAllBridge">全部通过</el-button>
          <el-button v-else :loading="allSubmitLoading" size="mini" @click="submitAllBridge">全部提交</el-button>
        </template>

        <template slot="beforeColumns">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <BridgePhoto :key="1" photoType="front" :photoUrl="getMediumUrl" :thumbnailUrl="getMiniUrl" :uploadUrl="uploadUrl" :data="scope.row" @onSuccess="handleUploadSuccess" @onView="handleView" @onRemove="handleRemove"></BridgePhoto>
              <BridgePhoto :key="2" photoType="side" :photoUrl="getMediumUrl" :thumbnailUrl="getMiniUrl" :uploadUrl="uploadUrl" :data="scope.row" @onSuccess="handleUploadSuccess" @onView="handleView" @onRemove="handleRemove"></BridgePhoto>
              <BridgePhoto :key="3" photoType="upward" :photoUrl="getMediumUrl" :thumbnailUrl="getMiniUrl" :uploadUrl="uploadUrl" :data="scope.row" @onSuccess="handleUploadSuccess" @onView="handleView" @onRemove="handleRemove"></BridgePhoto>
            </template>
          </el-table-column>
        </template>

        <template slot="afterColumns">
          <!-- 技术状况等级 -->
          <el-table-column label="等级" align="center" width="100px">
            <template slot-scope="scope">
              <el-popover
                v-if="!!scope.row.bridgeEvaluationMap && Object.keys(scope.row.bridgeEvaluationMap).length > 0"
                placement="left"
                trigger="hover">
                <Timeline style="margin-left: 8px;">
                  <Timeline-item v-for="[key, value] of Object.entries(scope.row.bridgeEvaluationMap)" :key="key">
                    <p class="evaluation-desc-title">{{key}}</p>
                    <template v-for="e of value">
                      <p class="evaluation-side-desc">{{e.sideTypeName+'('+e.superstructureTypeName+')'+'：'+(e.evaluationType === 0?'综合评分：'+e.sidePoint+' / ':'调整评分：')+e.sideLevel+'类'}}</p>
                    </template>
                  </Timeline-item>
                </Timeline>
                <el-tag slot="reference" :type="getBridgeEvaluationColor(scope.row.bridgeEvaluationLevel)" close-transition>{{!!scope.row.bridgeEvaluationLevel?scope.row.bridgeEvaluationLevel:'未评定'}}</el-tag>
              </el-popover>
            </template>
          </el-table-column>

          <!--检测状态-->
          <el-table-column style="padding-left: 5px;padding-right: 5px" label="检测状态" align="center" width="200px">
            <template slot-scope="scope">
              <el-popover
                placement="left"
                width="300"
                trigger="hover">
                <!--流程时间线-->
                <Timeline style="margin-left: 8px;">
                  <!--通过审核-->
                  <Timeline-item v-if="scope.row.status === 2" color="green">
                    <Icon type="trophy" slot="dot"></Icon>
                    <p style="font-weight: bold; font-size: small">{{scope.row.reviewDate}}</p>
                    <p style="padding-left: 2px;">审核通过</p>
                    <p style="padding-left: 2px;">审核人：{{currentTask.managerName}}</p>
                  </Timeline-item>
                  <!--打回-->
                  <Timeline-item v-if="!!scope.row.rejectDate" color="red">
                    <p style="font-weight: bold; font-size: small">{{scope.row.rejectDate}}</p>
                    <p style="padding-left: 2px;">审核未通过</p>
                    <p style="padding-left: 2px;">原因：{{scope.row.reason}}</p>
                    <p style="padding-left: 2px;">审核人：{{currentTask.managerName}}</p>
                  </Timeline-item>
                  <!--提交复核后-->
                  <Timeline-item v-if="!!scope.row.submitUserName" color="orange">
                    <p style="font-weight: bold; font-size: small">{{scope.row.submitDate}}</p>
                    <p style="padding-left: 2px;">复核完成，提交审核</p>
                    <p style="padding-left: 2px;">复核人：{{scope.row.submitUserName}}</p>
                  </Timeline-item>
                  <!--开始检测-->
                  <Timeline-item color="blue">
                    <p style="font-weight: bold; font-size: small">{{currentTask.startDate}}</p>
                    <p style="padding-left: 2px;">下发任务单，开始检测</p>
                  </Timeline-item>
                </Timeline>
                <!--流程条-->
                <el-steps slot="reference" class="none-title" :active="scope.row.status===-1?2:(scope.row.status+1)" center>
                  <el-step><template slot="icon">检</template></el-step>
                  <el-step><template slot="icon">复</template></el-step>
                  <el-step :status="scope.row.status===-1?'error':''"><template slot="icon">审</template></el-step>
                </el-steps>
              </el-popover>
            </template>
          </el-table-column>

          <!--操作按钮-->
          <el-table-column label="操作" align="center" width="180px">
            <template slot-scope="scope">
              <el-dropdown @command="handleInspection" trigger="click" style="margin-right: 8px">
                <el-button size="mini" type="info">
                  病害&nbsp;&nbsp;<Icon type="arrow-down-b"></Icon>
                </el-button>
                <el-dropdown-menu v-if="scope.row.bridgeSideList.length > 0" slot="dropdown">
                  <el-dropdown-item v-for="item of scope.row.bridgeSideList" :key="item.id" :command="item">{{item.sideTypeName}}</el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-menu v-else slot="dropdown">
                  <el-dropdown-item>无分幅信息</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button v-if="!isManager" :disabled="scope.row.status > 0" size="mini" type="warning" @click="submit(scope.row)">提交</el-button>
              <el-button v-if="isManager" :disabled="scope.row.status !== 1" size="mini" type="success" @click="pass(scope.row)">通过</el-button>
              <el-button v-if="isManager" :disabled="scope.row.status !== 1" size="mini" type="danger" @click="reject(scope.row)">打回</el-button>
            </template>
          </el-table-column>
        </template>

        <template slot="dialog">
          <Modal title="查看图片" width="50%" v-model="isPhotoVisible">
            <img :src="viewUrl" alt="图片加载失败或不存在" style="width: 100%;">
          </Modal>
        </template>
      </FrontSideTable>

      <!--病害管理界面-->
      <TaskBridgeDisease
        v-if="currentView === 1"
        :currentTask="currentTask"
        :currentSide="currentSide"
        :rootUrl="rootUrl"
        @onBack="handleDiseaseBack">
      </TaskBridgeDisease>
    </div>
  </div>
</template>

<script>
  import FrontSideTable from "../template/FrontSideTable.vue";
  import TaskBridgeDisease from "../template/TaskBridgeDisease.vue";
  import BridgePhoto from "../template/BridgePhoto.vue";
  import {doDelete, doGet, doPost} from "../../assets/js/utils/RequestUtils";
  import {DELETE, MANAGE} from "../../assets/js/enum/FunctionType";
  import {getAuthorizedFunction} from "../../assets/js/global";
  import {CONTEXT_PATH} from "../../assets/js/global";
  import {FRONT, SIDE, UPWARD} from "../../assets/js/enum/PhotoType";
  import {SUCCESS} from "../../assets/js/enum/RequestResult";
  import {getBridgeEvaluationColor, pointToLevel} from "../../assets/js/utils/EvaluationUtils";

  const UPDATE_URL = "/getSelectedBridgeById";

  export default {
    name:"TaskBridge",
    props:{
      rootUrl:{
        type:String,
        required:true
      },
      dataParam:{
        type:Object,
        required:true
      },
      tableTitle:{
        type:String,
        required:true
      },
      currentTask:{
        type:Object,
        required:true
      }
    },
    data() {
      return {
        currentView:0,
        columns: [
          {prop:"name", label:"桥名"},
          {prop:"roadNo", label:"路线号", width:"150", sortable:"custom"},
          {prop:"fullAddressName", label:"所在地"}
        ],
        searchProps:["name", "roadNo", "fullAddressName", "unitsName"],
        selectedBridgeList:[],
        allPassLoading:false,
        allSubmitLoading:false,
        //上传正、侧面照
        uploadUrl:CONTEXT_PATH+"/task/uploadBridgePhoto",
        getMiniUrl:CONTEXT_PATH+"/task/getMiniBridgePhoto",
        getMediumUrl:CONTEXT_PATH+"/task/getMediumBridgePhoto",
        viewUrl:"",
        isPhotoVisible:false,
        //点选进入病害管理界面
        currentSide:{}
      }
    },
    computed:{
      isManager() {
        return this.$store.state.User.currentUser.id === this.currentTask.manager;
      }
    },
    methods:{
      handleBack() {
        this.$emit("onBack");
      },
      handleDiseaseBack() {
        this.currentView = 0;
        this.$Loading.start();
        doGet(this.rootUrl + UPDATE_URL, {
          data:{
            taskId:this.currentSide.taskId,
            bridgeId:this.currentSide.bridgeId
          },
          componentId:this
        }).then(response=>{
          this.selectedBridgeList.filter(b=>b.id === this.currentSide.bridgeId).forEach(b=>{
            b.bridgeEvaluationLevel = response.bridgeEvaluationLevel;
            b.bridgeEvaluationMap = {};
            b.bridgeEvaluationMap = response.bridgeEvaluationMap;
          })
        })
          .finally(()=>{
            this.$Loading.finish();
            this.currentSide = {};
          });
      },
      handleCreated(data) {
        this.selectedBridgeList = data;
      },
      submit(data) {
        if(data.status < 1) {
          this.$Loading.start();
          doPost(this.rootUrl+"/submit", {
            data:{taskBridgeId:data.taskBridgeId},
            menuFunctionId:getAuthorizedFunction(this, MANAGE),
            component:this
          })
            .then(response=>this.$message({message:response.message, type:response.status.toLowerCase()}))
            .finally(()=>{
              this.$refs["table"].fetchData();
              this.$Loading.finish();
            });
        } else {
          this.$alert("桥梁已经提交", "提示");
        }
      },
      pass(data) {
        if(data.status === 1) {
          this.$Loading.start();
          doPost(this.rootUrl+"/pass", {
            data:{taskBridgeId:data.taskBridgeId},
            menuFunctionId:getAuthorizedFunction(this, MANAGE),
            component:this
          })
            .then(response=>this.$message({message:response.message, type:response.status.toLowerCase()}))
            .finally(()=>{
              this.$refs["table"].fetchData();
              this.$Loading.finish();
            });
        } else {
          this.$alert("桥梁不在待审核状态，无法提交审核", "提示");
        }
      },
      reject(data) {
        if(data.status === 1) {
          this.$prompt("请输入打回原因", "提示", {
            confirmButtonText:"打回",
            cancelButtonText:"取消"
          }).then(({value})=>{
            this.$Loading.start();
            doPost(this.rootUrl+"/reject", {
              data:{
                taskBridgeId:data.taskBridgeId,
                reason:value
              },
              menuFunctionId:getAuthorizedFunction(this, MANAGE),
              component:this
            })
              .then(response=>this.$message({message:response.message, type:response.status.toLowerCase()}))
              .finally(()=>{
                this.$refs["table"].fetchData();
                this.$Loading.finish();
              });
          }).catch(()=>{
            this.$message({
              type: 'info',
              message: '取消打回'
            });
          });
        } else {
          this.$alert("桥梁不在待审核状态，无法打回", "提示");
        }
      },
      submitAllBridge() {
        this.$confirm("桥梁提交审核之后，只有任务单下发人打回才能修改，确定全部提交?", "提示", {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }).then(()=> {
          if (this.selectedBridgeList.some(item => item.status < 1)) {
            this.allSubmitLoading = true;
            doPost(this.rootUrl + "/submitAllBridge", {
              data: this.selectedBridgeList.filter(item => item.status < 1).map(item => item.taskBridgeId),
              menuFunctionId: getAuthorizedFunction(this, MANAGE),
              component: this
            })
              .then(response => this.$message({message: response.message, type: response.status.toLowerCase()}))
              .finally(() => {
                this.$refs["table"].fetchData();
                this.allSubmitLoading = false;
              });
          } else {
            this.$alert("无待提交审核桥梁", "提示");
          }
        });
      },
      passAllBridge() {
        this.$confirm("桥梁通过审核之后，将作为历史数据保存，不能进行任何修改，确定全部通过?", "提示", {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }).then(()=> {
          if (this.selectedBridgeList.some(item => item.status === 1)) {
            this.allPassLoading = true;
            doPost(this.rootUrl + "/passAllBridge", {
              data: this.selectedBridgeList.filter(item => item.status === 1).map(item => item.taskBridgeId),
              menuFunctionId: getAuthorizedFunction(this, MANAGE),
              component: this
            })
              .then(response => this.$message({message: response.message, type: response.status.toLowerCase()}))
              .finally(() => {
                this.$refs["table"].fetchData();
                this.allPassLoading = false;
              });
          } else {
            this.$alert("无待审核桥梁", "提示");
          }
        });
      },
      handleInspection(side) {
        if(side) {
          this.currentSide = side;
          this.currentView = 1;
        }
      },
      handleUploadSuccess(response, data, photoType) {
        //界面反馈上传结果
        this.$message({message: response.message, type: response.status.toLowerCase()});
        //如果上传成功，更新结果
        if(response.status === SUCCESS) {
          //上传成功之后，更新照片路径
          switch (photoType) {
            case FRONT:
              data.frontPath = response.content;
              break;
            case SIDE:
              data.sidePath = response.content;
              break;
            case UPWARD:
              data.upwardPath = response.content;
              break;
          }
        }
      },
      handleView(url) {
        this.viewUrl = url;
        this.isPhotoVisible = true;
      },
      handleRemove(data, photoType) {
        this.$confirm("确定移除照片？", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          doDelete(this.rootUrl + "/removeBridgePhoto", {
            data:{...data, photoType},
            menuFunctionId:getAuthorizedFunction(this, DELETE),
            component:this
          }).then(response=>{
            if(response.status === SUCCESS) {
              //删除成功之后，更新照片路径
              switch (photoType) {
                case FRONT:
                  data.frontPath = "";
                  break;
                case SIDE:
                  data.sidePath = "";
                  break;
                case UPWARD:
                  data.upwardPath = "";
                  break;
              }
            }
            this.$message({message: response.message, type: response.status.toLowerCase()});
          });
        });
      },
      pointToLevel,
      getBridgeEvaluationColor
    },
    components:{FrontSideTable, BridgePhoto, TaskBridgeDisease}
  }
</script>

<style>
  .none-title {
    width:100%;
  }
  .none-title .el-step__main {
    display: none!important;
  }
  .evaluation-desc {
    padding-left: 6px;
    line-height: 1.2em;
  }
  .evaluation-side-desc {
    padding-left: 2px;
  }
  .evaluation-desc-title {
    font-weight: bold;
    font-size: small;
  }
</style>



// WEBPACK FOOTER //
// TaskBridge.vue?466aa741
